<template>
  <section class="org">
    <div class="container">
      <div style="height: 100%; overflow-y: auto; ">
      <div class="orgBox">
        <div class="item" v-for="(item,key,index) in orgData" :key="key">
          <div class="root">
            <div v-if="key==='selfList'" style="line-height: 30px; width: 140px;position: relative">
              <el-input placeholder="请输入内容" v-model="selfName"  size="mini"
                        @change="changeSelfName">
              </el-input>
             <span class="tips"> * 点击可重命名</span>
            </div>
            <span class="title" v-else>{{item.name}}</span>
          </div>
          <div class="cont">
            <ul>
              <li v-for="(itm) in item.data" :key="itm.id">
                <el-input placeholder="请输入内容" v-model="itm.name" size="mini" @change="renew(itm.id,itm.name)">
                  <template slot="append">
                    <el-button size="mini" @click="del(itm.id,itm.count,key)" title="删除">
                      <i class="el-icon-close"></i>
                    </el-button>
                  </template>
                </el-input>
              </li>
              <li class="add">
                <el-input placeholder="请输入内容" size="mini" v-model="addTemp[index]">
                  <template slot="append">
                    <el-button size="mini" @click="add(item.id,index)" title="新增">
                      <i class="el-icon-plus"></i>
                    </el-button>
                  </template>
                </el-input>
              </li>
            </ul>
          </div>
        </div>
      </div>
      </div>
      <Dialog :cfg="dialogCfg" ref="dialog">
        <div class="changeOrg">
          <h4 style="font-size: 14px; color:red; line-height: 40px">*当前单位下已存在用户，请先挪动这些用户到其他的单位！</h4>
          用户挪动到：
          <el-select v-model="changeOrgValue" placeholder="请选择单位" size="mini">
            <el-option
              v-for="item in changeOrgOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </div>
      </Dialog>

    </div>
  </section>
</template>

<script>
  import TableList from 'comp/common/TableList';
  import Dialog from 'comp/common/Dialog.vue';

  export default {
    name: "Org",
    components: {
      Dialog,
      TableList
    },
    data() {
      return {
        result: '',

        nav: 'org',
        unitName: '',
        selfName:'',
        addTemp: ['', '', ''],
        orgData: {},
        preOrgData: {},

        changeOrgOptions: [],
        changeOrgValue: '',


        tabHeight: 0,
        options: {
          username: '',
          trueName: '',
          mobile: '',
          unit: '',
          department: '',
          groups: ''

        },
        list: [],
        limit: 20,
        page: 1,
        pages: 1,
        totals: 0,
        column: [
          {
            prop: 'username',
            label: '用户名'
          },
          {
            prop: 'trueName',
            label: '姓名'
          },
          {
            prop: 'mobile',
            label: '手机号码'
          },
          {
            prop: 'company',
            label: '单位'
          },

          {
            prop: 'department',
            label: '部门'
          },
          {
            prop: 'post',
            label: '岗位'
          },
          {
            prop: 'groups',
            label: '群组'
          },
          {
            prop: '',
            label: '操作',
            btn: 'editAndDel',
            del: (id) => {
              this.delUser(id)
            },
            edit: (data) => {
              this.editUser(data)
            }
          }
        ],
        dialogCfg: {},
        editUserData: {
          username: '',
          realName: '',
          password: '',
          mobile: '',
          unit: '',
          department: '',
          post: '',
          groups: '',
          status: true
        },
        rules: {
          trueName: [
            {required: true, message: '请输入姓名', trigger: 'change'}
          ],
          password: [
            {required: true, message: '请输入密码', trigger: 'change'}
          ],
          mobile: [
            {required: true, message: '请输入手机号码', trigger: 'change'}
          ],
          company: [
            {required: true, message: '请输入单位', trigger: 'change'}
          ],
          department: [
            {required: true, message: '请输入部门', trigger: 'change'}
          ],
          post: [
            {required: true, message: '请选择岗位', trigger: 'change'}
          ]
        }

      }
    },
    mounted() {
      this.loadOrgList();
      this.loadList();

    },
    methods: {
      loadOrgList() {
        this.$server('org.list').then(data => {
          this.unitName=this.$kkui.cache.get('unit');
          this.selfName=this.unitName;
          let orgData = {};
          data.forEach(item => {
            if (item.name === '公路中心' || item.name === this.unitName) {
              orgData.selfList = {
                name: this.unitName,
                id: item.id,
                data: item.children,
                count: item.count
              };
            } else if (item.name === '各分中心') {
              orgData.centerList = {
                name: '事件处置中心/单位',
                id: item.id,
                data: item.children,
                count: item.count
              };
            } else {
              orgData.linkList = {
                name: '联动单位',
                id: item.id,
                data: item.children,
                count: item.count
              };
            }
          });
          this.preOrgData = orgData;
          this.orgData = JSON.parse(JSON.stringify(this.preOrgData));
        })
      },

      renew(id, name) {
        if (!name.trim()) {
          this.$kkui.msg({
            icon: 0,
            cont: '内容不能为空！',
            time: 1000
          });

          this.orgData = JSON.parse(JSON.stringify(this.preOrgData));
          return false;
        }

        this.$server('org.renewOrg', {
          id, name
        }).then(data => {
          this.loadOrgList();
        }).catch(err => {
          this.loadOrgList();
        })
      },

      add(pid, index) {
        if (this.addTemp[index]) {
          this.$server('org.addOrg', {
            pid,
            name: this.addTemp[index]
          }).then(data => {
            this.loadOrgList();
            this.addTemp[index] = '';
          })
        } else {
          this.$kkui.msg({
            icon: 0,
            cont: '内容不能为空！',
            time: 1000
          })
        }
      },
      del(id, count, key) {
        if (count) {
          const tempArr = [...this.orgData[key]['data']];
          tempArr.splice(tempArr.findIndex(item => item['id'] === id), 1);

          if (tempArr.length === 0) {
            this.$kkui.msg({
              icon: 0,
              time: 5000,
              cont: '删除失败！当前单位下已存在用户，且没有其他的单位可挪动这些用户，请新建单位后重新操作！'
            });
            return false;
          }

          this.changeOrgOptions = tempArr;

          this.dialogCfg = {
            title: '删除单位',
            closeShow: 1,
            footerShow: 1,
            width: 500,
            height: 200,
            submit: () => {
              this.$server('org.delOrg', `?deptId=${id}&organizationId=${this.changeOrgValue}`).then(data => {
                this.$kkui.msg({
                  cont: '删除成功！'
                });
                this.loadOrgList();
                this.$refs.dialog.show = 0;
                this.changeOrgOptions = [];
                this.changeOrgValue = '';
              })
            }
          };
          this.$refs.dialog.show = 1;


        } else {
          this.$server('org.delOrg', `?deptId=${id}&organizationId`).then(data => {
            this.loadOrgList();
          })
        }
      },

      changeSelfName(){
        if(this.selfName){
          this.$server('org.unitName', {
            realName: this.selfName
          }).then(data => {
            this.$kkui.cache.set('unit', this.selfName);
          })
        }else{
          this.$kkui.msg({icon:0, cont: '名称不能为空！'});
          this.selfName=this.unitName;
        }
      },


      //加载列表
      loadList() {
        this.$server('org.userList', {
          limit: this.limit,
          page: this.page,
          ...this.options
        }).then(data => {
          this.list = data['rows'].map(item => {
            return {
              ...item,
              status: item['status'] === '1',
            }
          });
          this.totals = data['total'];
          this.$kkui.loading_deepBlue.hide();
        })
      },

      //新增用户
      addUser() {
        this.rules.password[0].required = true;
        this.dialogCfg = {
          title: '新增用户',
          closeShow: true,
          footerShow: true,
          width: 615,
          height: 430,
          bg: true,
          submit: (callback) => {
            this.$refs['addForm'].validate((valid) => {
              if (valid) {
                this.$server('org.addUser', this.editUserData).then(data => {
                  this.loadList();
                  this.$kkui.msg({
                    icon: 1,
                    cont: '新增成功！'
                  });
                  this.initEditData();
                  typeof callback === 'function' && callback();
                });
              } else {
                return false;
              }
            });
          }
        };
        this.$refs.dialog.show = true;
      },

      //编辑用户
      editUser(data) {
        this.editUserData = {...data};
        this.rules.password[0].required = false;
        this.dialogCfg = {
          title: '编辑用户',
          closeShow: true,
          footerShow: true,
          width: 615,
          height: 430,
          bg: true,
          submit: (callback) => {
            this.$refs['addForm'].validate((valid) => {
              if (valid) {
                this.$server('org.renewUser', {
                  ...this.editUserData,
                  status: this.editUser.status ? '1' : '0'
                }).then(data => {
                  this.loadList();
                  this.$kkui.msg({
                    icon: 1,
                    cont: '编辑成功！'
                  });
                  this.initEditData();
                  typeof callback === 'function' && callback();
                });
              } else {
                return false;
              }
            });
          }
        };
        this.$refs.dialog.show = true;
      },

      //删除用户
      delUser(id) {
        this.$kkui.alert({
          icon: 0,
          cont: '确定删除此用户吗？',
          callback: () => {
            this.$server('org.delUser', [id * 1]).then(data => {
              this.loadList();
            })
          }
        });
      },

      initEditData() {
        this.editUserData = {
          username: '',
          realName: '',
          password: '',
          mobile: '',
          unit: '',
          department: '',
          post: '',
          groups: '',
          status: true
        }
      },

      // 下载模板
      downloadTab() {
        const index = this.$kkui.loading.show();
        this.$server('org.userTemplate', {
          tempalteName: 'user'
        }).then(data => {
          const a = document.createElement('a');
          a.href = data;
          a.style.display = 'none';
          a.target = '_blank';
          a.download = '用户表' + '.xls';
          a.click();
          setTimeout(() => {
            this.$kkui.loading.hide(index);
          }, 3000)
        })
      },

      //导入用户表
      importTab() {
        this.$kkui.submit({
          title: '上传用户表格',
          file: true,
          cont: '1'
        }, formData => {
          this.$kkui.alert({
            icon: 0,
            cont: '导入表格将会替换掉相同手机号或用户名的数据，确定吗？',
            callback: () => {
              this.$server('org.importUserTable', formData).then(data => {
                this.$kkui.msg({
                  icon: 1,
                  cont: '操作成功！'
                });
              })
            }
          })
        })
      },


      //切换分页
      changePage(page) {
        this.page = page;
        this.loadList();
      },

      changeSize(limit) {
        this.limit = limit;
        this.loadList();
      },

      // 重置option
      resetOption(formName) {
        this.$refs[formName].resetFields();
        this.loadList();
      },
    }
  }
</script>

<style scoped lang="scss">
  @import "~css/system.scss";

  .orgBox {
    height: 100%;
    display: flex;
    justify-content: center;
    gap: 50px;


    .item {
      display: flex;
      align-items: center;
    }


    .root {
      padding-right: 20px;
      position: relative;
      &::before{
        content: '';
        border-top: 1px solid #DCDFE6;
        position: absolute;
        width: 20px;
        height: 0;
        right: 0;
        top: 50%;
      }

      span.title {
        display: inline-block;
        color: #555;
        height: 30px;
        padding: 0 15px;
        line-height: 30px;
        font-size: 14px;
        font-weight: 600;
        border: 1px solid #DCDFE6;
        text-align: center;
        background-color: #f9f9f9;
      }

      span.tips{
        position: absolute;
        bottom: -30px;
        font-size: 12px;
        color:red;
        width: 100%;
        left: 0;
        text-align: center;
      }
      /deep/ .el-input--mini .el-input__inner{
        height: 30px;
        line-height: 30px;
        font-weight: 600;
        font-size: 14px;
        border-radius: 0;
        background-color: #f9f9f9;
        text-align: center;
        cursor: pointer;
      }

    }


    .cont {
      width: 230px;

    }

    ul {
      padding-left: 30px;

      li {
        /*display: flex;*/
        position: relative;
        padding: 5px 0;

      }

      li::after {
        content: '';
        border-bottom: 1px solid #DCDFE6;
        position: absolute;
        width: 30px;
        height: 0;
        left: -30px;
        top: 50%;
      }

      li::before {
        content: '';
        border-left: 1px solid #DCDFE6;
        position: absolute;
        width: 0;
        height: 100%;
        left: -30px;
        top: 0;
      }

      li:first-child:before {
        height: 50%;
        top: 50%;
      }

      li:last-child:before {
        height: 50%;
      }
    }

    /deep/ .el-input-group__append, .el-input-group__prepend {
      background-color: rgba(182, 145, 37, .8);
      color: #fff;
      opacity: .8;

      button {
        font-size: 12px;
      }
    }

    .add {
      /deep/ .el-input-group__append, .el-input-group__prepend {
        background-color: #03AAD3;
      }
    }

    /deep/ .el-input-group__append:hover, .el-input-group__prepend:hover {
      opacity: 1;
    }
  }

  .changeOrg {
    font-size: 14px;
  }

</style>
